﻿using Finbuckle.MultiTenant.Abstractions;
using Microsoft.EntityFrameworkCore;
using MultiTenant.SeparateSchema.Api.Extensions;
using MultiTenant.SeparateSchema.Api.Models;

namespace MultiTenant.SeparateSchema.Api.Data.Context;

public class ApplicationDbContext(
    DbContextOptions<ApplicationDbContext> options,
    IMultiTenantContextAccessor multiTenantContextAccessor)
    : DbContext(options)
{
    public DbSet<Product> Products { get; set; }
    public AppTenantInfo GetCurrentTenant()
    {
	    var tenantInfo = multiTenantContextAccessor.MultiTenantContext.TenantInfo as AppTenantInfo;
	    return tenantInfo  ?? throw new InvalidOperationException();
    }
    protected override void OnModelCreating(ModelBuilder builder)
    {
	    var tenantInfo = GetCurrentTenant();
	    builder.HasDefaultSchema(tenantInfo.SchemaName);
    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
	    optionsBuilder.UseTenantModelCacheKey();
    }
}
